package com.cctc.rds.raft.sdk.client.rpc.election;

import com.cctc.rds.nrpc.api.exception.RpcIOException;
import com.cctc.rds.nrpc.api.rpc.RpcRequest;
import com.cctc.rds.nrpc.api.rpc.RpcResponse;
import com.cctc.rds.nrpc.core.client.NettyRpcClient;
import com.cctc.rds.raft.core.rpc.election.ElectionRpc;
import com.cctc.rds.raft.core.rpc.election.ElectionRpcRequest;
import com.cctc.rds.raft.core.rpc.election.ElectionRpcResponse;

public class ElectionRpcRequestImpl implements ElectionRpc {
    private NettyRpcClient client;

    public ElectionRpcRequestImpl(NettyRpcClient client) {
        this.client = client;
    }

    @Override
    public ElectionRpcResponse elect(ElectionRpcRequest request) {
        RpcRequest rpcRequest = RpcRequest.builder()
                .interfaces(ElectionRpc.class)
                .methodName("elect")
                .parameterTypes(new Class<?>[]{ElectionRpcRequest.class})
                .arguments(new Object[]{request})
                .build();
        try {
            RpcResponse rpcResponse = client.remoteInvoke(rpcRequest);
            if (rpcResponse.getException() != null) {
                throw new RuntimeException(rpcResponse.getException());
            }
            return (ElectionRpcResponse) rpcResponse.getResult();
        } catch (RpcIOException e) {
            throw new RuntimeException(e);
        }
    }
}
